/*
 * SwingSimulationOneRun.java
 *
 * Created on Pondelok, 2007, november 12, 10:07
 *
 */

package logic;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.swing.SwingWorker;

/**
 *
 * @author alvin
 */
public class SwingSimulationOneRun extends SwingWorker<LinkedList<Statistic>, SimulationRunState> {

    public interface StateChangeListener {
        public void StateChanged(SimulationRunState newState);
        public void simulationFinished();
    }
    public void addStateChangeListener(StateChangeListener listener) {
        stateListeners.add(listener);
    }
    private Collection<StateChangeListener> stateListeners;
    
    
    SimulationRunState stav;
    private class WorkerState extends SimulationRunState {
        public void setState(int newState) {
            super.setState(newState);
            publish(this);
        }
        public void incDoneTasksCount() {
            super.incDoneTasksCount();
            publish(this);
        }
    }
    
    /**
     * Creates a new instance of SwingSimulationOneRun
     */
    public SwingSimulationOneRun() {
        stateListeners = new LinkedList<StateChangeListener>();
        stav = new WorkerState();
        publish(stav);
    }

    protected LinkedList<Statistic> doInBackground() throws Exception {
        JSimulation.start(stav);
        publish(stav);
        return JSimulation.getStatistics();
    }

    public void done() {
        for (StateChangeListener schl : stateListeners) 
            schl.simulationFinished();
    }
   
    public void stopExecuting() {
//        JSimulation.stop();
    }
    
    /**
     * invoked in event thread
     */
    protected void process(List<SimulationRunState> chunks) {
        SimulationRunState last = chunks.get(chunks.size() - 1);
        final SimulationRunState newState = new SimulationRunState(last);
        javax.swing.SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                for (StateChangeListener schl : stateListeners) 
                    schl.StateChanged(newState);
            }
        }
        );
    }
    
}
